<template>
  <div>
    <el-card class="box-card">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      </el-breadcrumb>

      <el-row :gutter="20">
        <el-col>
          <el-button type="primary" @click="showAddCategory()">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 树形表格控件 -->
      <!--      <zk-table :data="categories" :columns="columns" border show-index index-text="#" :selection-type="false"
                      :expand-type="false">
              <template slot="cat-deleted" slot-scope="scope">
                <i v-if="scope.row.cat_deleted" class="el-icon-error" style="color: #E47470"></i>
                <i v-else class="el-icon-success" style="color: #84C359"></i>
              </template>
              <template slot="order" slot-scope="scope">
                <el-tag v-if="scope.row.cat_level === 0" type="primary">一级</el-tag>
                <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
                <el-tag v-else-if="scope.row.cat_level === 2" type="warning">三级</el-tag>
              </template>
              <template slot="operation" slot-scope="scope">
                <el-button type="primary" @click="showEditCategoryDialog(scope.row.cat_id)">编辑</el-button>
                <el-button type="danger" @click="deleteCategory(scope.row)">删除</el-button>
              </template>
            </zk-table>-->

      <!-- element-ui的树形表格控件 -->
      <el-table
        :data="categories"
        row-key="cat_id"
        border
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="cat_id" label="分类id"></el-table-column>
        <el-table-column prop="cat_name" label="分类名称"></el-table-column>
        <el-table-column label="是否有效">
          <template v-slot="scope">
            <i v-if="scope.row.cat_deleted" class="el-icon-error" style="color: #E47470"></i>
            <i v-else class="el-icon-success" style="color: #84C359"></i>
          </template>
        </el-table-column>
        <el-table-column prop="cat_pid" label="父分类id"></el-table-column>
        <el-table-column label="分类当前层级">
          <template v-slot="scope">
            <el-tag v-if="scope.row.cat_level === 0" type="primary">一级</el-tag>
            <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
            <el-tag v-else-if="scope.row.cat_level === 2" type="warning">三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" @click="showEditCategoryDialog(scope.row.cat_id)">编辑</el-button>
            <el-button type="danger" @click="deleteCategory(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页插件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,5,10,20,50]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 新增分类对话框 -->
    <el-dialog
      title="添加分类"
      @close="closeAddCategory('addCategoryRef')"
      :visible.sync="addCategoryDialogVisible">
      <el-form :rules="addCategoryRules" ref="addCategoryRef" :model="addCategoryForm" label-width="90px">
        <el-form-item prop="cat_name" label="分类名称:">
          <el-input v-model="addCategoryForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <el-cascader
            clearable
            v-model="selectKeys"
            :options="parentCategories"
            :props="parentCategoryProps"
            @change="handleParentCategoriesChange"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
        <el-button :loading="addCategoryProhibit" type="primary" @click="addCategory('addCategoryRef')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCategoryDialogVisible">
      <el-form :rules="editCategoryRules" ref="editCategoryRef" :model="editCategoryForm" label-width="90px">
        <el-form-item prop="cat_name" label="分类名称:">
          <el-input v-model="editCategoryForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCategoryDialogVisible = false">取 消</el-button>
        <el-button :loading="editCategoryProhibit" type="primary"
                   @click="editCategory('editCategoryRef')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import common from '@/assets/js/common'
export default {
  created () {
    this.getCategories()
  },
  data () {
    return {
      loading: false,
      // 新增分类确认按钮是否禁用
      addCategoryProhibit: false,
      // 编辑分类确认按钮是否禁用
      editCategoryProhibit: false,
      // 编辑分类对话框是否显示
      editCategoryDialogVisible: false,
      // 分页查询参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 10
      },
      // 分类列表数据
      categories: [],
      // 总数量
      total: 0,
      // 字段映射关系
      /* columns: [
        {
          label: '分类id',
          prop: 'cat_id'
        },
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'cat-deleted'
        },
        {
          label: '父分类id',
          prop: 'cat_pid'
        },
        {
          label: '分类当前层级',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operation'
        }
      ], */
      // 新增分类对话框是否显示
      addCategoryDialogVisible: false,
      // 新增分类表单
      addCategoryForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 新增分类校验规则
      addCategoryRules: {
        cat_name: this.config.rules.categoryNameRules
      },
      // 新增分类父分类列表
      parentCategories: [],
      // 新增分类选中的父分类key
      selectKeys: [],
      // 新增分类中父分类级联选择框内容渲染 value label
      parentCategoryProps: {
        expandTrigger: 'hover',
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name'
      },
      // 编辑分类表单数据
      editCategoryForm: {},
      // 编辑分类校验规则
      editCategoryRules: {
        cat_name: this.config.rules.categoryNameRules
      }
    }
  },
  methods: {
    // 获取分类列表
    async getCategories () {
      this.loading = true
      const { data: res } = await this.http.get('categories', { params: this.queryInfo })
      this.total = res.data.total
      this.categories = res.data.result
      this.loading = false
    },
    // 分页大小改变
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getCategories()
    },
    // 当前页码改变
    handleCurrentChange (newPageNum) {
      this.queryInfo.pagenum = newPageNum
      this.getCategories()
    },
    async showAddCategory () {
      const { data: res } = await this.http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
      this.parentCategories = res.data
      this.addCategoryDialogVisible = true
    },
    handleParentCategoriesChange (parentCate) {
      this.addCategoryForm.cat_level = parentCate.length
      if (parentCate.length > 0) {
        this.addCategoryForm.cat_pid = parentCate[parentCate.length - 1]
      }
    },
    closeAddCategory (formName) {
      this.selectKeys = []
      this.$refs[formName].resetFields()
    },
    // 新增分类
    addCategory (formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return this.$message.error('请正确填写表单')
        await common.preventDuplicateSubmit(prohibit => {
          this.addCategoryProhibit = prohibit
        }, async () => {
          const { data: res } = await this.http.post('categories', this.addCategoryForm)
          if (res.meta.status !== 201) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
          this.$message.success(`${res.meta.status} ${res.meta.msg}`)

          this.addCategoryDialogVisible = false
          this.$refs[formName].resetFields()
          this.addCategoryForm = {
            cat_pid: 0,
            cat_name: '',
            cat_level: 0
          }
          await this.getCategories()
        })
      })
    },
    async deleteCategory (category) {
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'cancel') return
      const { data: res } = await this.http.delete(`categories/${category.cat_id}`)
      if (res.meta.status !== 200) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
      this.$message.success(`${res.meta.status} ${res.meta.msg}`)
      await this.getCategories()
    },
    async showEditCategoryDialog (id) {
      const { data: res } = await this.http.get(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
      this.editCategoryForm = res.data
      this.editCategoryDialogVisible = true
    },
    editCategory (formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return this.$message.error('请正确填写表单')
        await common.preventDuplicateSubmit(prohibit => {
          this.editCategoryProhibit = prohibit
        }, async () => {
          const { data: res } = await this.http.put(`categories/${this.editCategoryForm.cat_id}`, { cat_name: this.editCategoryForm.cat_name })
          if (res.meta.status !== 200) return this.$message.error(`${res.meta.status} ${res.meta.msg}`)
          this.$message.success(`${res.meta.status} ${res.meta.msg}`)
          this.editCategoryDialogVisible = false
          this.$refs[formName].resetFields()
          this.editCategoryForm = {}
          await this.getCategories()
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.zk-table {
  margin-top: 15px;
  margin-bottom: 15px;
  font-size: 13px;
}

.zk-table__cell-inner {
  padding-top: 2px !important;
  padding-bottom: 0 !important;
}

.el-cascader {
  width: 100%;
}
</style>
